<template>
  <div id="main">
    <h2>排课管理</h2>
    <div class="head">
      <el-button
        type="primary"
        style="margin:20px"
        @click="handleOpen('添加排课', 1)"
      >添加排课</el-button>

      <!-- -------------------------------------列表展示区-------------------------------------------------------------------- -->

      <el-input
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width:240px;float: right;margin:20px;"
      />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="clazz.className"
          label="班级名称"
        />

        <el-table-column
          align="center"
          prop="room.roomLoc"
          label="使用房间"
        />
        <el-table-column
          align="center"
          prop="staff.staffName"
          label="排课人员姓名"
        />

        <el-table-column
          align="center"
          prop="timeDay"
          label="上课日期"
        />

        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改排课', 2, Scope.row.scheduleId)"
            >编辑/查看</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(Scope.row.scheduleId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- -------------------------------------列表展示区-------------------------------------------------------------------- -->

    <!-- -------------------------------------添加信息区-------------------------------------------------------------------- -->
    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="staff"
        :model="staff"
        label-position="top"
        :rules="rules"
      >
        <el-form-item
          prop="classId"
          label="班级名称"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="staff.classId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in Class"
              :key="j.classId"
              :label="j.className"
              :value="j.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="roomId"
          label="使用房间"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="staff.roomId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in room"
              :key="j.roomId"
              :label="j.roomLoc"
              :value="j.roomId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="teacherId"
          label="授课老师"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="staff.teacherId"
            filterable
            placeholder="请选择"
            style="width: 100%;"
          >
            <el-option
              v-for="j in staff0"
              :key="j.staffId"
              :label="j.String"
              :value="j.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="timeSkcd"
          label="第几节开始的课"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.timeSkcd"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item
          prop="timeSkjc"
          label="上课占几节段"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.timeSkjc"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          prop="scheduleColor"
          label="排课显示颜色"
          :label-width="formLabelWidth"
        >
          <!-- <el-input v-model="staff.scheduleColor" autocomplete="off" /> -->
          <el-color-picker v-model="staff.scheduleColor" />
        </el-form-item>
        <el-form-item
          prop="fontColor"
          label="字体颜色"
          :label-width="formLabelWidth"
        >
          <!-- <el-input v-model="staff.fontColor" autocomplete="off" /> -->
          <el-color-picker v-model="staff.fontColor" />
        </el-form-item>
        <el-form-item
          label="上课日期"
          :label-width="formLabelWidth"
          prop="timeStarttoString"
        >
          <el-date-picker
            v-model="staff.timeDay"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            style="width: 100%;"
          />
          <!-- </el-form-item>
        <el-form-item
          prop="weekName"
          label="周几"
          :label-width="formLabelWidth"
        > -->
          <el-input
            v-model="staff.weekName"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleClose"
        >取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('staff')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddSchedule('staff')"
        >添 加</el-button>
      </div>
    </el-dialog>
    <!-- -------------------------------------添加信息区-------------------------------------------------------------------- -->
  </div>
</template>
<script>
import {
  getAllSchedule,
  deleteSchedule,
  updateSchedule,
  AddSchedule,
  getScheduleById
} from '@/api/schedule'
import { getAllRoomName } from '@/api/room'
import { getAllClass } from '@/api/class'
import { getStaffStringT } from '@/api/staff'
export default {
  data () {
    return {
      readValue: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      studentId: '',
      // list: [],
      tableList: [],
      searchTableInfo: '',
      staff0: [],
      Class: {},
      classList: {},
      room: [],
      name: '',
      search: '',
      listLoading: false,
      dialogFormVisible: false,
      jurisdiction: [],
      editType: 1, // 1 添加 2 修改
      staff: {},
      formLabelWidth: '200px ',
      rules: {
        // classCompletionTimes: [{ required: true, message: '上课次数不能为空', trigger: 'blur' }],
        // classCourseId: [{ required: true, message: '课程ID不能为空', trigger: 'blur' }],
        // classMedicalDirectorId: [{ required: true, message: '医疗主管ID不能为空', trigger: 'blur' }],
        // classResponsibleTeacherId: [{ required: true, message: '责任老师ID不能为空', trigger: 'blur' }],
        // classStatus: [{ required: true, message: '课程状态不能为空', trigger: 'blur' }],
        // classTeacherId: [{ required: true, message: '授课老师ID不能为空', trigger: 'blur' }],
        // classTeachingDirectorId: [{ required: true, message: '教学主管ID不能为空', trigger: 'blur' }],
        // classTimes: [{ required: true, message: '课时数量不能为空', trigger: 'blur' }],
        // classType: [{ required: true, message: '班级类型不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list () {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created () {
    this.fetchData()
    this.getAllRoom()
    this.getAllclass()
    this.getAllStaffA()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function (size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    handleClick (row) {
      console.log(row)
    },

    getAllRoom () {
      getAllRoomName().then(res => {
        this.room = res.obj
        console.log('d获取所有房间', this.room)
      })
    },
    getAllclass () {
      getAllClass().then(res => {
        this.Class = res.obj
        console.log('所有班级', this.Class)
      })
    },
    getAllStaffA () {
      getStaffStringT().then(res => {
        console.log(res)
        this.staff0 = res.obj
      })
    },
    fetchData () {
      this.listLoading = true
      getAllSchedule().then(data => {
        this.tableList = data.obj
        this.listLoading = false
        console.log('列表信息：', this.list)
      })
    },

    handleDelete (id) {
      this.$confirm('确认删除该条排课？此条排课Id为' + id).then(() =>
        deleteSchedule(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },

    handleAddSchedule (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.staff.timeDaytoString = this.staff.timeDay
          AddSchedule(this.staff).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.staff = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'erro，r'
          })
          console.log('添加的信息为：', this.staff)
          return false
        }
      })
    },
    handleOpen (title, type, id) {
      this.staff = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getScheduleById(id).then(res => {
          console.log(res)
          this.staff = res.obj
          console.log(this.staff)
        })
      }
    },
    handleClose () {
      this.dialogFormVisible = false
      this.staff = {}
    },
    handleUpdate (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.staff.timeDaytoString = this.staff.timeDay
          updateSchedule(this.staff).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
